from django.shortcuts import render
from web.forms.file import FileFolderModelForm
from django.http import JsonResponse
from web import models

def file(request,project_id):

    parent_object = None
    floder_id = request.GET.get('folder', '')
    if floder_id.isdecimal():
        parent_object = models.FileRepository.objects.filter(id=int(floder_id), file_type=2,
                                                             project_id=request.tracer.project_id).first()
    # 文件列表
    if request.method == 'GET':
        breadcrumb_list = []
        parent = parent_object.parent
        while parent :
            breadcrumb_list.insert(0, {'id':parent.id, 'name':parent.name})
            parent = parent.parent
        query_set =models.FileRepository.objects.filter(project=request.tracer.project)
        if parent_object:
            file_object_list = query_set.filter(parent=parent_object).order_by('-file_type')
        else:
            file_object_list = query_set.filter(parent__isnull=True).order_by('-file_type')
        form = FileFolderModelForm(request,parent_object)
        context = {'form':form,
                   'file_object_list':file_object_list,
                   'breadcrumb_list':breadcrumb_list,}

        return render(request,'file.html',context)

    # post添加文件夹 &文件夹的修改
    fid = request.POST.get('fid','')
    edit_object = None
    if fid.isdecimal():
        edit_object = models.FileRepository.objects.filter(id=int(fid), file_type=2,project=request.tracer.project).first()

    if edit_object:
        form = FileFolderModelForm(request,parent_object,data=request.POST,instance=edit_object)
    else:
        form = FileFolderModelForm(request, parent_object, data=request.POST)

    if form.is_valid():
        form.instance.project = request.tracer.project
        form.instance.update_user = request.user
        form.instance.parent = parent_object
        form.instance.file_type = 2
        form.save()
        return JsonResponse({'status':True,'error':form.errors})
    return JsonResponse({'Status':False,'error':form.errors})
